<?php
namespace haibao\cms\data;

use \haibao\frame\data\query\Condition;
use \haibao\cms\model\filter\ProductCategoryProperty as PropertyFilter;
use \haibao\cms\model\filter\ProductCategoryDefine as CategoryFilter;

class ProductCategoryProperty extends \haibao\cms\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\cms\model\data\ProductCategoryProperty');
	}
	
	/**
	 * @param $propertyFilter \haibao\cms\model\filter\ProductCategoryProperty
	 */
	public function getAll($propertyFilter){
		return parent::getAll($propertyFilter);
	}
	
	/**
	 * 删除属性
	 */
	public function deleteProperty($propertyId,$arrSet){
		parent::updateById($propertyId, $arrSet);
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$model = $this->getOneById($propertyId);
			$this->deleteOldProperty($model);
		}
	}
	
	/**
	 * 获取当前分类最大的排序
	 */
	public function getMaxOrder($categoryId){
		$max = null;
		$sql = "select max(OrderNo) as max from ProductCategoryProperty where categoryId=%s AND Status = %s";
		$result  = $this->query($sql,array(
				$categoryId,\haibao\cms\model\data\ProductCategoryProperty::STATUS_ENABLE
				));
		
		while ($result->fetch_assoc()){
			$max = $result->getData('max');
		}
		return $max;
	}
	/**
	 * 根据属性id查找
	 */
	public function getPropertyById($propertyId){
		$propertyFilter = new PropertyFilter();
		$categoryFilter = new CategoryFilter();
		$propertyFilter->select(array(
				PropertyFilter::CONDITION_FIELD_NAME_ID,
				PropertyFilter::CONDITION_FIELD_NAEM_ORDERNO,
				PropertyFilter::CONDITION_FIELD_NAME_CATEGORY_ID,
				PropertyFilter::CONDITION_FIELD_NAME_DATA_TYPE,
				PropertyFilter::CONDITION_FIELD_NAME_DEFAULT_VALUE,
				PropertyFilter::CONDITION_FIELD_NAME_PROPERTY_NAME,
				PropertyFilter::CONDITION_FIELD_NAME_SELECT_DATA_VALUE
				));
		$categoryFilter->select(array(
				CategoryFilter::CONDITION_FIELD_NAME_CATEGORY_NAME,
				CategoryFilter::CONDITION_FIELD_NAME_ID
				));
		$propertyFilter->leftJoin($categoryFilter,null,PropertyFilter::CONDITION_FIELD_NAME_CATEGORY_ID,CategoryFilter::CONDITION_FIELD_NAME_ID,PropertyFilter::CONDITION_FIELD_NAME_CATEGORY,false);
		$propertyFilter->where(PropertyFilter::CONDITION_FIELD_NAME_STATUS, Condition::CONDITION_EQUAL, \haibao\cms\model\data\ProductCategoryProperty::STATUS_ENABLE);
		$propertyFilter->where(PropertyFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_EQUAL, $propertyId);
		return $this->getOne($propertyFilter);
	}
	/**
	 * @param \haibao\cms\model\data\ProductCategoryProperty $categoryPropertyModel
	 */
	public function add($model){
		self::beginTranscation();
		try{
			parent::add($model);
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			$oldId = $this->addOldProperty($model);
			$this->addDataMigrationMap($model,$oldId);
		}
	}
	/**
	 * @param array()\haibao\cms\model\data\ProductCategoryProperty $categoryPropertyModels
	 */
	public function addAll($models){
		self::beginTranscation();
		try{
			foreach($models as $key=>$model){
				parent::add($model);
				$models[$key] = $model;
			}
		
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){
			foreach($models as $key=>$model){
				$oldId = $this->addOldProperty($model);
				$this->addDataMigrationMap($model,$oldId);
			}
		}
	}
	/**
	 * 
	 * @param \haibao\cms\model\data\ProductCategoryProperty $categoryPropertyModel
	 */
	public function save($model){
		self::beginTranscation();
		try{
			parent::updateById($model->Id, array(
					PropertyFilter::CONDITION_FIELD_NAEM_ORDERNO =>$model->OrderNo,
					PropertyFilter::CONDITION_FIELD_NAME_DATA_TYPE => $model->DataType,
					PropertyFilter::CONDITION_FIELD_NAME_DEFAULT_VALUE => $model->DefaultValue,
					PropertyFilter::CONDITION_FIELD_NAME_PROPERTY_NAME => $model->PropertyName,
					PropertyFilter::CONDITION_FIELD_NAME_SELECT_DATA_VALUE =>$model->SelectDataValue,	
					));
		}catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		$this->endTranscation();
		if(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::SYNC_OLD)){	
			$this->updateOldProperty($model);
		}
	}
	
	/**
	 * 删除子孩子属性
	 * @param  int $id
	 */
	public function deleteSnycSubProperty($id){
		$property = $this->getOneById($id);
		$propertyName = $property->PropertyName;
		
		$propertyFilter = new PropertyFilter();
		$propertyFilter->where(PropertyFilter::CONDITION_FIELD_NAME_PROPERTY_NAME, Condition::CONDITION_EQUAL, $propertyName);
		$propertyFilter->where(PropertyFilter::CONDITION_FIELD_NAME_ID, Condition::CONDITION_NOTEQUAL, $id);
		
		parent::remove($propertyFilter);
	}
	
	public function addSubCategoryProperty($model){
		$sql = 'insert into ProductCategoryProperty
				(
				(select %s as CategoryId from ProductCategoryMap where ParentId = %s)
				union 
				(select * from ProductCategoryProperty where Id= %s)
				) a';
	}
	
	/**
	 *
	 * @param string $tableName
	 * @param int $newPrimaryKey
	 */
	public function getDataMigration($tableName,$newPrimaryKey){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
	
		$sql  ="select `PrimaryKey`,`OldPrimaryKey` from DataMigrationMap where TableName=%s and PrimaryKey =%s";
		$result = $this->query($sql,array(
				$tableName,$newPrimaryKey
		));
		$oldPrimaryKey = null;
		while ($result->fetch_assoc()){
			$oldPrimaryKey = $result->getData('OldPrimaryKey');
		}
		return $oldPrimaryKey;
	}
	
	private function getOldCategory($id){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
	
		$sql = "select `cateid`,`parent_cateid`,`level` from `brand_category` where `cateid` = %s";
		$result = $this->query($sql,array($id));
		$arrSet = array();
		while($result->fetch_assoc()){
			$arrSet['cateid'] = $result->getData('cateid');
			$arrSet['parentId'] = $result->getData('parent_cateid');
			$arrSet['level'] = $result->getData('level');
			$arrSet['cateid'] = $result->getData('cateid');
		}
		return $arrSet;
	}
	private function addDataMigrationMap($model,$oldPrimaryKey){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS );
	
		$tableName = $model->getTableName();
		$sql = "insert into `DataMigrationMap`(`TableName`,`PrimaryKey`,`OldPrimaryKey`)values(%s,%s,%s)";
		$this->query($sql,array($tableName,$model->Id,$oldPrimaryKey));
	}
	private function addOldProperty($model){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		
		$oldCateid = $this->getDataMigration('ProductCategoryDefine',$model->CategoryId);
		if($oldCateid){
			$cateInfo = $this->getOldCategory($oldCateid);
			$oldParentId = $cateInfo['parentId'];
			if(!$oldParentId){
				$oldParentId = $oldCateid;
				$oldCateid = 0;
			}
			$sql = "insert into `brand_category_paramsmall` (`cateid`, `cateid2`, `param_name`, `input_tag`, `input_value`,`input_sort`,`username`,`date`) values(%s, %s, %s, %s, %s,%s,%s,%s)";
			if($model->DataType){
				switch($model->DataType){
					case  2:
					case  4:
						$inputType = 2;
						$inputValue = $model->SelectDataValue;
						break;
					case 1:
					case 3:
						$inputType = 1;
						$inputValue = $model->DefaultValue;
						break;
				}
			}
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$this->query($sql,array($oldParentId,$oldCateid,$model->PropertyName,$inputType,implode(',', json_decode($inputValue,true)),0,'admin',$model->CreateTime));
			return $this->getDb()->insert_id;
		}
	}
	
	public function updateOldProperty($model){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		
		$oldCateid = $this->getDataMigration('ProductCategoryDefine',$model->CategoryId);
		$cateInfo = $this->getOldCategory($oldCateid);
		$oldParentId = $cateInfo['parentId'];//$this->getDataMigration('ProductCategoryDefine',$cateInfo['parentId']);
		if(!$oldParentId){
			$oldParentId = 0;
		}
		$sql = "update `brand_category_paramsmall` set `cateid` = %s, `cateid2` =%s, `param_name`= %s, `input_tag`=%s, `input_value`=%s where id = %s";
		if($model->DataType){
			switch($model->DataType){
				case  2:
				case  4:
					$inputType = 2;
					$inputValue = $model->SelectDataValue;
					break;
				case 1:
				case 3:
					$inputType = 1;
					$inputValue = $model->DefaultValue;
					break;
			}
		}
		$oldId = $this->getDataMigration($model->getTableName(),$model->Id);
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
		$this->query($sql,array($oldParentId,$oldCateid,$model->PropertyName,$inputType,$inputValue,$oldId));
	}
	
	private function deleteOldProperty($model){
		$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
	
		$tableName = $model->getTableName();
		$oldId =  $this->getDataMigration($tableName,$model->Id);
		if($oldId){
			$this->setConfig( \haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_ARTICLE );
			$sql = "delete from `brand_category_paramsmall` where id=%s";
			$this->query($sql,array($oldId));
		}
	}
}
